'use strict'

process.chdir(__dirname)


const titbit = require('titbit')
const fs = require('fs')
const pg = require('pg');
const dbconfig = require('./dbconfig.js')
const wxkey = require('./wxkey')

const tbloader = require('titbit-loader')
//使用HTTP/1.1客户端
const { httpcli } = require('gohttp')

const token = require('titbit-token')

let tok = new token({
    //有效期秒数
    expires: 30,
    //32位
    key: 'ljljljljljljljljljljljljljljljlj',
    //16位
    iv: 'ljliujingliujing'
})

//初始化数据连接
let psql = new pg.Pool(dbconfig)

try {
    fs.accessSync('./images')
} catch (err) {
    fs.mkdirSync('./images')
}

let cert_path = '/usr/local/share'

const app = new titbit({
    //开启模式调试，会输出错误信息
    debug: true,
    cert: `${cert_path}/api.qasdwer.xyz.pem`,
    key: `${cert_path}/api.qasdwer.xyz.key`
})

let tb = new tbloader();
tb.init(app);

//在app.service对象上添加了一个属性
app.addService('tok',tok);
app.addService('psql',psql);

app.addService('imagePath',`${__dirname}/images`)


//c是context
app.get('/', async c => {
    c.send('ok')
})

app.get('/upload', async c => {
    //c.helper是助手函数模块，其中有对stream.pipe的封装
    //c.reply是响应对象，http/1.1中指向response
    await c.helper.pipe('./upload.html', c.reply)
})

//立即执行函数，前面加;用于区分代码块
//;(async()=>{})();
app.get('/user/:name/:age/:mobile', async c => {
    console.log(c.param)
    c.send(c.param)
})

app.get('/mp-login/:code', async c => {
    c.send(c.param)
    let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
        + `?appid=${wxkey.appid}`
        + `&secret=${wxkey.secret}`
        + `&js_code=${c.param.code}`
        + `&grant_type=authorization_code`

    let ret = await httpcli.get(auth_url)
        .then(res => {
            return res.json()
        })

    c.send(tok.make(ret))
})

//监听1234 端口
app.run(2021)

